package com.lanxiao.cloud.common.web.service.impl;

import cn.hutool.core.convert.ConverterRegistry;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.lanxiao.cloud.common.core.constant.LanXiaoConstant;
import com.lanxiao.cloud.common.core.dto.UserAgentDto;
import com.lanxiao.cloud.common.core.service.IOperatorService;
import com.lanxiao.cloud.common.core.utils.StringUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author ：qiaoliang
 * @date ：2021-08-19
 */
@Service
public class OperatorServiceImpl implements IOperatorService {

  @Override
  public Long operator() {
    try{
      final String header = this.request().getHeader(LanXiaoConstant.X_CURRENT_ID);
      return ConverterRegistry.getInstance().convert(Long.class, header);
    }catch (Exception e){
      return null;
    }
  }

  @Override
  public String ip() {
    return this.request().getHeader(LanXiaoConstant.X_IP);
  }

  @Override
  public UserAgentDto<Long> getUserAgent() {
    final HttpServletRequest request = this.request();
    final String header = this.request().getHeader(LanXiaoConstant.X_CURRENT_ID);

    final UserAgent parse = UserAgentUtil.parse(this.request().getHeader(LanXiaoConstant.USER_AGENT));
    String decode = "";
    try {
      final String cityName = request.getHeader(LanXiaoConstant.X_CITY_NAME);
      if(StringUtils.isNotBlank(cityName)) {
        decode = URLDecoder.decode(cityName,
            "UTF-8");
      }
    } catch (UnsupportedEncodingException ignored) {
    }
    return new UserAgentDto<>(
        ConverterRegistry.getInstance().convert(Long.class, header),
        request.getHeader(LanXiaoConstant.X_IP),
        decode
        ,
        parse.getBrowser().toString(),
        parse.getOs().toString()
    );
  }

  private HttpServletRequest request () {
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    return ((ServletRequestAttributes) requestAttributes).getRequest();
  }

}
